import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_play_android/ui/base/base_widget.dart';
import 'package:flutter_play_android/widgets/custom_view.dart';

class CustomPaper extends CustomPainter {
  final List<List<TolyCircle>> lines;
  final List<TolyCircle>? positions;
  late final Paint _paint;

  CustomPaper(this.lines, {this.positions}) {
    _paint = Paint()
      ..color = Colors.purple //画笔颜色
      ..strokeCap = StrokeCap.round //画笔笔触类型
      ..isAntiAlias = true //是否启动抗锯齿
      // ..blendMode = BlendMode.srcOut //颜色混合模式
      ..style = PaintingStyle.stroke //绘画风格，默认为填充
      // ..colorFilter = const ColorFilter.mode(Colors.blueAccent,
      //     BlendMode.srcIn) //颜色渲染模式，一般是矩阵效果来改变的,但是flutter中只能使用颜色混合模式
      // ..maskFilter =MaskFilter.blur(BlurStyle.inner, 5.0)
      // const MaskFilter.blur(BlurStyle.inner, 3.0) //模糊遮罩效果，flutter中只有这个
      ..filterQuality = FilterQuality.high //颜色渲染模式的质量
      ..strokeWidth = 5.0; //画笔的宽度
  }

  @override
  void paint(Canvas canvas, Size size) {
    if (positions != null && positions!.isNotEmpty) {
      drawLine(canvas, positions!);
    }
    for (var value in lines) {
      for (var pos in value) {
        pos.color = Colors.purple;
      }
      drawLine(canvas, value);
    }
  }

  void drawLine(Canvas canvas, List<TolyCircle> positions) {
    //注意这里是positions.length - 1
    for (var i = 0; i < positions.length - 1; i++) {
      if (positions[i] != null && positions[i + 1] != null) {
        canvas.drawLine(positions[i].pos, positions[i + 1].pos,
            _paint..strokeWidth = positions[i].radius);
        _paint.color = positions[i].color ?? Colors.red;
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

class TolyDrawable {
  Offset pos;
  Color? color;

  TolyDrawable(this.pos, this.color);
}

class TolyCircle extends TolyDrawable {
  double radius;

  TolyCircle(Color color, Offset pos, {this.radius = 4.0}) : super(pos, color);
}

class PaperScreen extends BaseWidget {
  const PaperScreen({Key? key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> attachState() => _PaperScreenState();
}

class _PaperScreenState extends BaseWidgetState {
  final _positions = <TolyCircle>[];
  final _lines = <List<TolyCircle>>[];

  @override
  void initState() {
    showContent();
    super.initState();
  }

  //按下时表示新添加一条线,并记录上一点位置
  void _panDown(DragDownDetails details) {
    var x = details.localPosition.dx;
    var y = details.localPosition.dy;
    // _oldPos = Offset(x, y);
    print('pan down ${_positions.toString()}');
    //panDown 也记录一个点
    setState(() {
      // _lines.add(_positions);
      _positions.add(TolyCircle(Colors.blue, Offset(x, y), radius: 4.0));
    });
  }

  ///移动中，将点添加到点集中
  void _panUpdate(DragUpdateDetails details) {
    print('pan update');
    var x = details.localPosition.dx;
    var y = details.localPosition.dy;
    var curPos = Offset(x, y);
    var tolyCirle = TolyCircle(Colors.blue, curPos, radius: 4.0);
    setState(() {
      _positions.add(tolyCirle);
    });
  }

  /// 抬起后，将旧线拷贝到线集中
  void _panEnd(DragEndDetails details) {
    var oldLine = <TolyCircle>[];
    oldLine.addAll(_positions);
    setState(() {
      _lines.add(oldLine);
      _positions.clear();
    });
  }

  @override
  AppBar attachAppBar() => AppBar(title: const Text("画板"));

  @override
  Widget attachContentWidget(BuildContext context) => GestureDetector(
        child: Stack(
          children: [
            CustomPaint(
              painter: CustomPaper(_lines, positions: _positions),
              // painter: CustomView(Colors.black54),
              size: const Size(double.infinity, double.infinity),
            ),
            Positioned(
                child: TextButton(
              child: const Text("clear"),
              onPressed: () {
                setState(() {
                  _positions.clear();
                  _lines.clear();
                });
              },
            ))
          ],
        ),
        onPanStart: (DragStartDetails details) {
          print('pan start');
          //从start开始记录点更流畅一些
          var x = details.localPosition.dx;
          var y = details.localPosition.dy;
          setState(() {
            _positions.add(TolyCircle(Colors.blue, Offset(x, y), radius: 4.0));
          });
        },
        onPanDown: _panDown,
        onPanUpdate: _panUpdate,
        onPanEnd: _panEnd,
      );

  @override
  void onClickErrorWidget() {}
}
